"""
SQL编译器 V2.0
完全符合实践要求：整合词法分析、语法分析、语义分析、执行计划生成
"""

from .lexer_v2 import SQLLexerV2
from .parser_v2 import SQLParserV2
from .semantic_v2 import SemanticAnalyzerV2
from .execution_plan import ExecutionPlanGenerator

class SQLCompilerV2:
    """SQL编译器 V2.0"""
    
    def __init__(self):
        """初始化编译器"""
        self.lexer = SQLLexerV2()
        self.parser = SQLParserV2()
        self.semantic_analyzer = SemanticAnalyzerV2()
        self.plan_generator = ExecutionPlanGenerator()
    
    def compile(self, sql_text: str) -> dict:
        """编译SQL语句，返回完整结果"""
        result = {
            'sql': sql_text,
            'tokens': [],
            'ast': None,
            'semantic_result': None,
            'execution_plan': None,
            'errors': []
        }
        
        try:
            # 1. 词法分析
            print("1. 词法分析:")
            tokens = self.lexer.tokenize(sql_text)
            result['tokens'] = tokens
            self.lexer.print_tokens()
            
            # 2. 语法分析
            print("\n2. 语法分析:")
            ast = self.parser.parse(sql_text)
            result['ast'] = ast
            if ast:
                print("AST构建成功:")
                self.parser.print_ast(ast)
            else:
                print("AST构建失败")
                result['errors'].append("语法分析失败")
                return result
            
            # 3. 语义分析
            print("\n3. 语义分析:")
            semantic_result = self.semantic_analyzer.analyze(ast)
            result['semantic_result'] = semantic_result
            
            if self.semantic_analyzer.has_errors():
                print("语义错误:")
                for error in self.semantic_analyzer.get_errors():
                    print(f"  {error}")
                    result['errors'].append(str(error))
                return result
            else:
                print("语义分析通过")
            
            # 4. 执行计划生成
            print("\n4. 执行计划生成:")
            execution_plan = self.plan_generator.generate_plan(ast)
            result['execution_plan'] = execution_plan
            
            if execution_plan:
                print("执行计划生成成功:")
                self.plan_generator.print_plan_tree(execution_plan)
                
                print("\nJSON格式:")
                print(execution_plan.to_json())
                
                print("\nS表达式格式:")
                print(execution_plan.to_s_expression())
            else:
                print("执行计划生成失败")
                result['errors'].append("执行计划生成失败")
            
        except Exception as e:
            print(f"编译错误: {str(e)}")
            result['errors'].append(str(e))
        
        return result
    
    def get_catalog(self):
        """获取系统目录"""
        return self.semantic_analyzer.get_catalog()
    
    def print_catalog(self):
        """打印系统目录"""
        self.semantic_analyzer.print_catalog()

# 测试函数
if __name__ == "__main__":
    compiler = SQLCompilerV2()
    
    # 测试用例
    test_cases = [
        "CREATE TABLE student(id INT PRIMARY KEY, name VARCHAR(50), age INT);",
        "INSERT INTO student VALUES (1, 'Alice', 20);",
        "SELECT id, name FROM student WHERE age > 18;",
        "DELETE FROM student WHERE id = 1;"
    ]
    
    for i, test_case in enumerate(test_cases):
        print(f"\n{'='*60}")
        print(f"测试用例 {i+1}: {test_case}")
        print('='*60)
        
        result = compiler.compile(test_case)
        
        if result['errors']:
            print(f"\n编译失败，错误: {result['errors']}")
        else:
            print(f"\n编译成功！")
    
    print(f"\n{'='*60}")
    print("最终系统目录:")
    compiler.print_catalog()
